package loader;

import javafx.concurrent.Task;
import model.SlidingBox;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * 关卡加载器
 */
public class SlidingBoxLoader extends Task<SlidingBox> {
    /**
     * 关卡文件
     */
    private File file;

    public SlidingBoxLoader(File file) {
        this.file = file;
    }

    /**
     * 加载成功后返回关卡数据
     *
     * @return 加载并构建完成的滑块盒实例
     **/
    @Override
    protected SlidingBox call() throws Exception {
        SlidingBox slidingBox = new SlidingBox();
        slidingBox.setPrevSlidingBox(null);
        slidingBox.buildBlocks(this.loadData(this.file));
        slidingBox.setSteps(0);
        return slidingBox;
    }

    /**
     * 加载关卡数据
     *
     * @param file 关卡文件
     *
     * @return 关卡数据数组
     **/
    private char[][] loadData(File file) throws IOException {
        char[][] stageData = new char[5][4];
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        this.updateMessage("开始加载关卡数据: "+file.toString());
        String line;
        for (int currentRow = 0; currentRow < stageData.length; currentRow++) {
            line = bufferedReader.readLine();
            for (int currentCol = 0; currentCol < line.length(); currentCol++) {
                char code = line.charAt(currentCol);
                stageData[currentRow][currentCol] = code;
            }
        }
        bufferedReader.close();
        this.updateMessage("关卡数据加载完毕.");
        return stageData;
    }
}
